﻿using CPPEI.Coolzon.UI;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace CPPEI.Coolzon.Designer.Views
{
    [ValueConversion(typeof(Metadata.PartLibItem), typeof(string))]
    public class TypeToIconSourceConverter : IValueConverter
    {
        public static readonly string DEFAULTICONSOURCE = "./Null.gif";
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return DEFAULTICONSOURCE;
            }
            Metadata.PartLibItem partLibItem = value as Metadata.PartLibItem;
            if(string.Equals(partLibItem.Name, "Pointer"))
            {
                return "./指针.png";
            }
            if(string.IsNullOrWhiteSpace(partLibItem.Assembly) || string.IsNullOrWhiteSpace(partLibItem.Type))
            {
                return DEFAULTICONSOURCE;
            }
            try
            {
                string assemblyFile = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, partLibItem.Assembly);
                if (!assemblyFile.EndsWith(".dll"))
                {
                    assemblyFile += ".dll";
                }
                Assembly assembly = Assembly.LoadFile(assemblyFile);
                Type type = assembly.GetType(partLibItem.Type);

                XPartIconAttribute attribute = (XPartIconAttribute)Attribute.GetCustomAttribute(type, typeof(XPartIconAttribute));
                if (attribute == null)
                {
                    return DEFAULTICONSOURCE;
                }
                else
                {
                    return attribute.Source;
                }
            }
            catch
            {
                return DEFAULTICONSOURCE;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
